package top.yqingyu.httpserver.controller;


import top.yqingyu.httpserver.annotation.QyController;
import top.yqingyu.httpserver.common.HttpMethod;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.ArrayList;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.httpserver.controller.WakeUp
 * @description
 * @createTime 2022年11月23日 02:32:00
 */
@QyController(path = "WakeUp")
public class WakeUp {

    private static String HEADER = "FF:FF:FF:FF:FF:FF";

    @QyController(path = "/all", method = HttpMethod.GET)
    public String wakeUpAll() throws IOException {
        ArrayList<String> hosts = new ArrayList<>();
        hosts.add("192.168.50.66");
        hosts.add("192.168.50.67");
        hosts.add("192.168.50.68");
        ArrayList<String> macs = new ArrayList<>();
        macs.add("50-EB-F6-78-31-DF");
        macs.add("50:EB:F6:78:31:DE");
        macs.add("DC:21:5C:B7:64:DE");
        macs.add("E0:D5:5E:8D:7A:BB");

        for (String host : hosts) {
            for (String mac : macs) {
                sendMagicPackage(host,mac);
            }
        }

        return "wakeUp";
    }

    @QyController(path = "/pc", method = HttpMethod.GET)
    public String wakeUp() throws IOException {
        Runtime.getRuntime().exec("etherwake -i enp7s0 50:EB:F6:78:31:DE").destroy();
        Runtime.getRuntime().exec("etherwake -i enp7s0 50:EB:F6:78:31:DF").destroy();
        return "复活吧！我的爱人！";
    }

    public void sendMagicPackage(String host, String mac) throws IOException {
        StringBuilder sb = new StringBuilder(HEADER);
        for (int i = 0; i < 16; i++) {
            sb.append(":");
            sb.append(mac);
        }
        DatagramChannel channel = DatagramChannel.open();
        ByteBuffer byteBuffer = getHexByteBuffer(sb.toString());
        channel.send(byteBuffer, new InetSocketAddress(host, 7));
        channel.close();
    }

    static ByteBuffer getHexByteBuffer(String packet) {
        String[] split = packet.split("([:]|[-])");
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(split.length);
        for (int i = 0; i < split.length; i++) {
            byteBuffer.put(i, (byte) Integer.parseInt(split[i], 16));
        }
        return byteBuffer;
    }

}
